package advanced.network.basic_servlet;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.util.ArrayList;
import java.util.List;


/**
 * 自定义的webhandler, 继承默认的handler
 * 用来解析xml中的标签
 */
public class WebHandler extends DefaultHandler {

    private List<Entity> entities;
    private List<Mapping> mappings;
    private Entity entity;
    private Mapping mapping;
    private String tag;
    private boolean isMapping = false;//

    public WebHandler() {
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        String contents = new String(ch, start, length).trim();
        if (tag != null) {//处理空
            if (isMapping) {
                if (tag.equals("servlet-name")) {
                    mapping.setName(contents.toString());
                } else if (tag.equals("url-pattern")) {
                    mapping.addPattern(contents);
                }
            } else {
                //操作servlet
                if (tag.equals("servlet-name")) {
                    entity.setName(contents.toString());
                } else if (tag.equals("servlet-class")) {
                    entity.setClz(contents);
                }
            }
        }
    }

    @Override
    public void startDocument() throws SAXException {
        //初始化容器,存储解析后的数据
        entities = new ArrayList<>();
        mappings = new ArrayList<>();

    }


    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        if (qName != null) {
            tag = qName;//存储标签名
            if (qName.equals("servlet")) {
                entity = new Entity();
                isMapping = false;
            } else if (tag.equals("servlet-mapping")) {
                mapping = new Mapping();
                isMapping = true; //表示正在解析mapping
            }
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        if (qName != null) {
            if (qName.equals("servlet")) {
                entities.add(entity);

            } else if (qName.equals("servlet-mapping")) {
                mappings.add(mapping);
            }
        }
        tag = null;
    }

    public List<Entity> getEntitis() {
        return entities;
    }

    public List<Mapping> getMappings() {
        return mappings;
    }
}
